from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet

from models import SKU
from .models import User
from rest_framework.generics import  GenericAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework import mixins
from .import serializers
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection

class CheckUsernameView(APIView):
    def get(self,request,username):
        #根据用户名查询
        count = User.objects.filter(username=username).count()
        #返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)
class CheckMobileView(APIView):
    def get(self,request,mobile):
        #根据手机号查询，用户数量
        count = User.objects.filter(mobile=mobile).count()
        #返回响应
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)
class RegisterUserView(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializers
    # def post(self,request):
        #第一种只继承序列化注册方法
        #1.获取参数
        # dict_data = request.data
        # 2.创建序列化器，校验
        # serializer = self.get_serializer(data=dict_data)
        # serializer.is_valid(raise_exception=True)
        #
        # 3.数据入库
        # serializer.save()
        # 4返回响应
        # return  Response(serializer.data,status=status.HTTP_201_CREATED)
        #使用MIXIN

class UserInfoView(GenericAPIView):
    serializer_class = serializers.UserInfoSerializer

    permission_classes = [IsAuthenticated]#认证的用户
    def get_object(self):
        return self.request.user
    #单纯使用二级试图
    def get(self,request):
        # 单纯使用二级试图
        #1.获取用户对象（或者request.user)
        user = self.get_object()
        #2.创建序列化对象
        serializer = self.get_serializer(instance = user )

        #3.返回数据
        return Response(serializer.data)

        #二级视图配合mixin
        # return self.retrieve(request)

class EmailSendView(UpdateAPIView):
    serializer_class= serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user

class EmailActiveView(APIView):
    def get(self,request):
        #1.获取参数token
        token = request.query_params.get("token")

        #2.为空校验
        if not token :
            return Response(status=status.HTTP_400_BAD_REQUEST)

        #3,解密token
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        #4数据入库（修改email_active属性）
        user.email_active = True
        user.save()
        #5,返回响应
        return  Response(status=status.HTTP_200_OK)

class AddressView(mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,GenericViewSet):
    serializer_class =serializers.AddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    def list(self,request):
        #1.获取用户地址信息
        queryset = self.get_queryset()
        #2.获取序列化器
        serializers = self.get_serializer(instance=queryset,many=True)
        #3.返回
        return  Response ({
            "addresses":serializers.data,
            "limit":20,
            "default_address_id":request.user.default_address_id
        })
    def create(self, request, *args, **kwargs):
         #获取用户地址数量
        count = request.user.addresses.filter(is_deleted=False).count()
         #判断地址的数量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        #调用父类方法即可
        return super(AddressView,self).create(request,*args,**kwargs)
    #2更改用户默认地址
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.sava()
        return Response(status=status.HTTP_200_OK)
    #3.修改地址的标题
    @action(methods=["put"],detail=True)
    def title(self,request,pk):
        #1.获取参数
        dict_data = request.data
        address = self.get_object()
        #2.创建序列化
        serializer = serializers.AddressTitleSerializer(instance=address,data=dict_data)
        #3.校验数据，入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        #4.返回

        return Response(serializer.data)

    #4.重写destory方法，为了逻辑删除
    def destory(self,request,*args,**kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)



class TestView(APIView):
    def get(self,request,name,age):
        print(self.kwargs)
        return Response("%s,%s"%(name,age))

class UserBrowerHistoryView(CreateAPIView,RetrieveAPIView):
    serializers_class = serializers.UserBrowerHistorySerializer

    def get(self, request):
        #1.获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%request.user.id,0,4)

        #2,拼接数据
        sku_list =[]
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url":sku.default_image_url,
                "name":sku.name,
                "price":sku.price,
                "comments":sku.comments,
                "id":sku.id
            }
            sku_list.append(sku_dict)

        #3.返回
            return Response({"skus":sku_list})